package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.constant.ChatMessageConstant;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.dto.chat.ConversationDto;
import com.example.everying.model.dto.content.ActivityArticleDto;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.entity.content.ActivityApply;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.vo.chat.ChatMessageVo;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import com.example.everying.service.content.ActivityApplyService;
import com.example.everying.service.content.ActivityArticleService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class CardMessageMessageHandler implements MessageHandler {

    private static ChatConversationService chatConversationService;
    private static ChatMessagesService chatMessageService;
    private static ActivityApplyService activityApplyService;
    private static ActivityArticleService activityArticleService;

    @Autowired
    private void setService(
            ChatConversationService chatConversationService,
            ChatMessagesService chatMessageService,
            ActivityApplyService activityApplyService,
            ActivityArticleService activityArticleService
    ) {
        CardMessageMessageHandler.chatConversationService = chatConversationService;
        CardMessageMessageHandler.chatMessageService = chatMessageService;
        CardMessageMessageHandler.activityApplyService = activityApplyService;
        CardMessageMessageHandler.activityArticleService = activityArticleService;
    }


    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        log.info("收到卡片信息");
        String userId = WebSocketChatService.getUserId(session);
        String toUserId = message.getString("userId");
        String bizId = message.getString("bizId");


        // 获取会话id
        ChatConversationEntity chatConversationEntity = chatConversationService.getConversation(userId, toUserId);
        ChatMessagesEntity entity = new ChatMessagesEntity();
        if (chatConversationEntity == null) {
            log.warn("会话不存在");
            return;
        }
        // 保存消息
        entity.setBizId(bizId);
        entity.setConversationId(chatConversationEntity.getId());
        entity.setFormUserId(userId);
        entity.setToUserId(toUserId);
        entity.setPostMessages("卡片信息");
        entity.setMsgStatus(ChatMessageConstant.MESSAGE_STATUS_UNREAD); // 默认未读
        entity.setTime(LocalDateTime.now());
        entity.setMessagesType(ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_CARD);
        entity.setType(ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_CARD); // 默认为文本消息
        String cardInfo = buildCardInfoJson(bizId, chatConversationEntity);
        entity.setCardInfo(cardInfo); // 记录此时文章状态
        boolean isSave = chatMessageService.save(entity);
        if (!isSave) {
            log.error("保存消息失败，内容为: {}", "卡片信息");
            return;
        }
        // 更新会话最后聊天id
        chatConversationService.updateLastMessageId(chatConversationEntity.getId(), entity.getId(), userId);
        // 构建响应JSON
        JSONObject resJson = buildResponseJson(userId, entity);
        JSONObject toResJson = buildResponseJson(toUserId, entity);


        // 给某个用户发消息
        WebSocketChatService.sendMessageToUserId(toUserId, toResJson.toJSONString());
        log.info("发送给对方{}的消息", toUserId);
        WebSocketChatService.sendMessageToUserId(userId, resJson.toJSONString());
        log.info("发送给自己{}的消息", userId);

        // 在重新发一个列表
        sendChatConversationList(userId);
        log.info("发送给自己{}的列表", userId);
        sendChatConversationList(toUserId);
        log.info("发送给对方{}的列表", toUserId);

    }

    /**
     * 构建卡片消息响应JSON对象
     *
     * @param userId 用户ID，用于判断消息发送者
     * @param entity 聊天消息实体对象
     * @return 包含消息类型、消息内容和会话ID的JSON响应对象
     */
    private JSONObject buildResponseJson(String userId, ChatMessagesEntity entity) {
        log.info("发送给{}的消息是{}", userId, entity);
        // 创建响应JSON对象并转换消息实体
        JSONObject resJson = new JSONObject();
        ChatMessageVo vo = chatMessageService.convertToDTO(entity);
        // 设置消息发送者标识
        vo.setSender(entity.getFormUserId().equals(userId));
        // 添加消息类型、消息内容和会话ID到响应JSON
        resJson.put("type", "cardMessage");
        resJson.put("message", vo);
        resJson.put("conversationId", entity.getConversationId());
        return resJson;
    }

    /**
     * 向指定用户发送聊天会话列表
     *
     * @param userId 用户ID，用于标识要发送消息的用户
     */
    protected void sendChatConversationList(String userId) {
        List<ConversationDto> conversations = chatConversationService.getUserConversations(userId);
        JSONObject result = new JSONObject();
        result.put("type", "messageList");
        result.put("conversations", conversations);
        int unreadCount = Math.toIntExact(chatMessageService.count(new QueryWrapper<ChatMessagesEntity>().eq("to_user_id", userId).eq("msg_status", ChatMessageConstant.MESSAGE_STATUS_UNREAD)));
        result.put("unreadNum", unreadCount);
        WebSocketChatService.sendMessageToUserId(userId, result.toJSONString());
    }

    /**
     * 构建卡片信息的JSON字符串
     *
     * @param bizId 业务ID，用于获取文章和申请记录
     * @return String 返回构建好的JSON字符串，如果找不到对应记录则返回null
     */
    private String buildCardInfoJson(String bizId, ChatConversationEntity chatConversationEntity) {
        ActivityArticle article = activityArticleService.getArticleById(bizId);
        if (article == null) {
            log.error("文章不存在");
            return null;
        }

        // 构建卡片信息
        ActivityArticleDto dto = new ActivityArticleDto();
        dto.setArticle(article);
        // 获取申请用户ID
        String applyUserId = getApplyUserId(chatConversationEntity, article);
        // 获取申请记录
        QueryWrapper<ActivityApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("art_id", bizId);
        queryWrapper.eq("user_id", applyUserId);
        ActivityApply apply = activityApplyService.getOne(queryWrapper);

        if ( apply != null) {
            dto.setIsPublic(true);
            dto.setApplyId(apply.getId());
            dto.setApplyStatus(activityArticleService.getApplyStatus(apply.getOrdersStatus(), article.getStatus(),article.getType()));
        } else  {
            if (article.getType() ==0 || article.getType() == 3){
                dto.setApplyStatus("10");
            }else {
                dto.setApplyStatus("0");
            }
            dto.setIsPublic(false);
        }


        return JSON.toJSONString(dto);
    }

    /**
     * 获取申请用户的ID
     *
     * @param chatConversationEntity 聊天对话实体
     * @param article                活动文章
     * @return 申请用户的ID
     */
    private String getApplyUserId(ChatConversationEntity chatConversationEntity, ActivityArticle article) {
        if (chatConversationEntity.getUser1Id().equals(article.getUserId())) {
            return chatConversationEntity.getUser2Id();
        } else {
            return chatConversationEntity.getUser1Id();
        }
    }
}
